package org.example.uhy.domain.model.upgrade.execution.node;


import org.example.uhy.domain.model.upgrade.execution.UpgradeExecutionContext;

public class MemberCountRuleExecutionNode extends ConditionUpgradeExecutionNode<Integer> {
    public static final String TYPE = "MEMBER_COUNT";

    public MemberCountRuleExecutionNode(Integer expectedValue) {
        super(expectedValue);
    }

    @Override
    public boolean match(UpgradeExecutionContext context) {
        Integer memberCount = getMembersCount(context);
        if (memberCount == null || memberCount == 0) {
            return false;
        }
        return memberCount >= getExpectedValue();
    }

    private Integer getMembersCount(UpgradeExecutionContext context) {
        if (context.hasCachedValue(TYPE)) {
            return context.getCachedValue(TYPE);
        }
        Integer membersCount = 0;
        if (!context.upgradeObject().isMember()) {
            membersCount = context.distributionRepository().membersCountOfDistributor(context.upgradeObject().distributorId());
        }
        context.setCachedValue(TYPE, membersCount);
        return membersCount;
    }

    @Override
    public String getType() {
        return TYPE;
    }
}
